<?php

namespace app\company\controller\report\subset;

use app\BaseController;
use app\model\not_del\RatingScaleModel as NotDelRatingScaleModel;
use app\model\not_del\UserModel as NotDelUserModel;
use app\model\ProxyEvaluationResultModel;
use app\model\RatingScaleModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskModel;
use app\model\TaskUserResultModel;
use app\model\UnitModel;
use app\model\UserModel;
use app\model\WarningReportRecordModel;
use think\App;

class WarningReport extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 预警报告记录
     * @return bool|string
     */
    public function Index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'unit_id|单位ID' => 'require'
            ]);
            $where = [];
            $WarningWhere = [];
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $WarningReportRecordModel = new WarningReportRecordModel();
            $UserModel = new NotDelUserModel();
            $TaskModel = new TaskModel();
            $RatingScaleModel = new NotDelRatingScaleModel();
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (isset($param['answer_role']) && strlen($param['answer_role']) > 0) {
                $where[] = ['answer_role', '=', $param['answer_role']];
            }
            if (!empty($param['department_id'])){
                $uid = $UserModel->where('department_id', '=', $param['department_id'])->column('uid');
                if (!empty($uid)) {
                    $where[] = ['uid', 'in', $uid];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            if (!empty($param['name'])){
                $task_id = $TaskModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                $rating_scale_id = $RatingScaleModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                $uid = $UserModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                $where_ids = array_merge($task_id,$rating_scale_id, $uid);
                if (count($where_ids)) {
                    $where_ids = array_unique($where_ids);
                }else{
                    $where_ids = [-1];
                }
                $where[] = ['task_id|rating_scale_id|uid', 'in', $where_ids];
            }
            if (!empty($param['source'])) {
                switch ($param['source']) {
                    case 1:
                        $id = $TaskUserResultModel->where($where)->column('id');
                        $WarningWhere[] = ['result_id', 'in', $id];
                        $WarningWhere[] = ['source', '=', 1];
                        break;
                    case 2:
                        $id = $SelfEvaluationResultModel->where($where)->column('id');
                        $WarningWhere[] = ['result_id', 'in', $id];
                        $WarningWhere[] = ['source', '=', 2];
                        break;
                    case 3:
                        $id = $ProxyEvaluationResultModel->where($where)->column('id');
                        $WarningWhere[] = ['result_id', 'in', $id];
                        $WarningWhere[] = ['source', '=', 3];
                        break;
                }
            } else {
                $id = $TaskUserResultModel->where($where)->column('id');
                $ids = $WarningReportRecordModel->where([
                    ['result_id', 'in', $id],
                    ['source', '=', 1],
                ])->column('id');
                $id2 = $SelfEvaluationResultModel->where($where)->column('id');
                $ids2 = $WarningReportRecordModel->where([
                    ['result_id', 'in', $id2],
                    ['source', '=', 2],
                ])->column('id');
                $id3 = $ProxyEvaluationResultModel->where($where)->column('id');
                $ids3 = $WarningReportRecordModel->where([
                    ['result_id', 'in', $id3],
                    ['source', '=', 3],
                ])->column('id');
                $ids = array_unique(array_merge($ids, $ids2, $ids3));
                $WarningWhere[] = ['id', 'in', $ids];
            }
            if (!empty($param['id'])) {
                if (is_array($param['id'])) {
                    $WarningWhere[] = ['id', 'in', $param['id']];
                } else {
                    $WarningWhere[] = ['id', '=', -1];
                }
            }
            $WarningWhere[] = ['unit_id', '=', $param['unit_id']];
            $query =$WarningReportRecordModel->where($WarningWhere);
            $data = $query->order('id desc')->paginate($param['pageSize'])->toArray();
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            foreach ($data['data'] as &$item) {
                switch ($item['source']) {
                    case 1:
                        $item['source_name'] = '任务测评';
                        $info = $TaskUserResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'task',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
                        break;
                    case 2:
                        $item['source_name'] = '自我测评';
                        $info = $SelfEvaluationResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
                        break;
                    case 3:
                        $item['source_name'] = '他人代测';
                        $info = $ProxyEvaluationResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
                        break;
                    default:
                        break;
                }
                if (!isset($info)) {
                    continue;
                }
                $item = [
                    'id' => $item['id'],
                    'user_name' => $info['user_name'],
                    'user_avatar' => $info['user_avatar'],
                    'age' => $info['age'],
                    'sex' => $info['sex'],
                    'warning_name' => $info['warning_name'],
                    'total_score' => $info['total_score'],
                    'task_name' => $info['task_name'] ?? '--',
                    'is_explain' => $info['is_explain'],
                    'source' => $item['source_name'],
                    'answer_role' => $info['answer_role'],
                    'rating_scale_name' => $info['rating_scale_name'],
                    'rating_scale_type_name' => $info['rating_scale_type_name'],
                    'unit_name' => $info['unit_name'],
                    'department_name' => $info['department_name'],
                    'department_admins' => $info['departmentAdmins'] ?? [],
                    'result_read_auth' => $info['result_read_auth'],
                    'time' => $info['time'],
                    'student_status' => $info['student_status'],
                    'username' => $info['username'],
                    'number' => $info['uid']
                ];
            }
            $data['ids'] = $query->column('id');
            $UnitModel = new UnitModel();
            $data['unit_name'] = $UnitModel->where('id','=',$param['unit_id'])->cache(true,60)->value('name');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}